/* eslint-disable no-undef */
import { getProjectDetial, listComment } from '@/api/task/taskDetail';
import _ from 'lodash';
import { getUserAvatar } from '@/pages/TaskDetail/common';
import { getAppId } from '@/utils/local'; //

// task list执行情况
const stakStatus = {
  resKey: 'xmwcqk',
  img: require('@/static/img/task/tasktype.png'),
  label: '执行情况：',
  value: '',
  showRightIcon: true,
  contentType: 1,
  rightFont: '',
  showRightFontBadge: true,
  action: (row, self) => mutations.taskImplementClick(row, self)
};

const state = {
  baseUrl: '',
  resData: {}, // 参考 不要改
  enterpriseGuid: '',
  taskList: [
    {
      resKey: 'csjProgramName',
      groupTitle: ''

    },
    {
      resKey: 'taskName',
      img: require('@/static/img/task/taskname.png'),
      label: '任务名称：',
      value: '',
      showRightIcon: false,
      contentType: 1
    },
    {
      resKey: 'status',
      img: require('@/static/img/task/tasktype.png'),
      label: '任务状态：',
      value: '',
      showRightIcon: true,
      contentType: 1,
      action: (row, self) => mutations.taskStatusClick(row, self)
    },
    // {
    //   resKey: 'xmwcqk',
    //   img: require('@/static/img/task/tasktype.png'),
    //   label: '执行情况：',
    //   value: '',
    //   showRightIcon: true,
    //   contentType: 1,
    //   action: (row, self) => mutations.taskImplementClick(row, self)
    // },
    {
      resKey: 'programTime',
      img: require('@/static/img/task/tasktime.png'),
      label: '项目时间：',
      value: '',
      showRightIcon: false,
      contentType: 1
    },
    {
      resKey: 'annexIds',
      img: require('@/static/img/task/tasklink.png'),
      label: '附件',
      showRightIcon: false,
      fileContent: [],
      contentType: 1

    },
    {
      resKey: 'remark',
      img: require('@/static/img/task/taskmemo.png'),
      label: '备注',
      contentType: 1,
      showRightIcon: false,
      fontContent: ''
    },
    {
      resKey: 'details',
      img: require('@/static/img/task/taskuser.png'),
      label: '参与人:',
      rightFont: '',
      contentType: 1,
      findKey: 'userList',
      usersInfo: [],
      showRightIcon: true,
      action: (row, self) => mutations.partUserRowClick(row, self)
    }
  ],

  // 聊天内容
  messageList: [
    {
      img: require('@/static/img/task/taskmsg.png'),
      label: '最新内容',
      showRightIcon: true,
      rightFont: '更多',
      contentType: 1,
      action: (row, self) => mutations.gotoMoreTownCommonMessage(row, self)
    }
  ],

  // more town
  moreTown: [],

  commentConfig: {},

  // resData中如何userid的乡镇数据
  detailsOne: {},

  townReject: false,

  // 详情页路由参数
  taskInfoRouteQuery: ''
};

const mutations = {
  assignBaseUrl(state, url) {
    state.baseUrl = url;
  },

  // 评论头像赋值
  assginCommentUserAvatar(state, { img, editUser }) {
    state.messageList.forEach(item => {
      if (item.contentType === 2 && item.cardMsg.editUser === editUser) {
        item.cardMsg.avatar = img;
      }
    });
  },

  commentConfigNomore(state) {
    state.commentConfig.isNextPage = false;
  },
  // 添加评论
  addComment(state, payload) {
    console.log(payload);
    const timeNow = new Date();
    const time = timeNow.getFullYear() + '-' + (timeNow.getMonth() + 1 + '').padStart(2, '0') + '-' + (timeNow.getDate() + '').padStart(2, '0');
    const p = _.cloneDeep(payload);

    const photolist = p.files.map(file => {
      return {
        img: file.b64 || file.path,
        path: file.path,
        type: file.type
      };
    });
    const data = {
      contentType: 2,
      cardMsg: {
        avatar: '',
        content: p.content,
        guid: p.taskGuid,
        name: uni.getStorageSync('userName') + `(${uni.getStorageSync('appRole')})`,
        editUser: uni.getStorageSync('userId'),
        photolist,
        time
      }
    };
    state.messageList.splice(1, 0, data);
  },
  // 删除评论
  delMessage(state, index) {
    state.messageList.splice(index, 1);
  },

  // 任务状态【行 点击
  taskStatusClick: (row, self) => {
    const query = window.location.href.split('?')[1];
    self.$router.push({
      path: `/taskdetail/tasktodo?${query}`
    });
  },

  // 参与人行点击
  partUserRowClick: (row, self) => {
    self.$router.push('/taskdetail/taskuserpart');
  },

  // 点击了最新内容 （乡镇评论分类）
  gotoMoreTownCommonMessage(row, self) {
    self.$router.push('/moretown' + `?taskGuid=${self.$route.query.guid}`);
  },

  // 执行情况点击
  taskImplementClick(row, self) {
    const query = window.location.href.split('?')[1];
    state.taskInfoRouteQuery = query;
    self.$router.push({
      path: '/taskdetail/implement'
    });
  },

  // 任务详情赋值
  assignValueForTask(state, payload) {
    state.resData = payload;
    // 特殊处理字段
    const keyMap = {
      csjProgramName: (item, value) => {
        item.groupTitle = value;
      },

      status: (item, value) => {
        const mapStatus = {
          1: '进行中',
          2: '已完成',
          3: '已延期',
          4: '待审核',
          5: '驳回'
        };
        item.value = mapStatus[value] || '未发布';
      },

      remark: (item, value) => {
        item.fontContent = value;
        if (value === '') {
          item.isHide = true;
        }
      },

      annexIds: (item, value) => {
        value && value.forEach(file => {
          file.fileName = file.originName;
        });
        item.fileContent = value || [];
      },

      details: async(item, value) => {
        const users = [];
        let userId = '';
        try {
          userId = uni.getStorageSync('userId');
        } catch (e) {
          // error
        }

        // 财政执行情况
        const taskNum = value.reduce((prev, curr) => {
          if (curr.status === 4) {
            prev += 1;
          }
          return prev;
        }, 0);

        const taskStatus = state.taskList.find(item => item.resKey === 'xmwcqk');
        if (taskStatus) {
          taskStatus.rightFont = taskNum + '';
        }

        value.forEach(item => {
          if (item.users && item.users.length) {
            item.users.forEach(user => {
              if (user.isCheck === 1) {
                if (userId === user.userId) {
                  state.enterpriseGuid = item.cEnterpriseCode;
                }
                users.push({
                  ...user,
                  userName: user.trueName,
                  userRole: '乡镇',
                  enterpriseName: item.enterpriseName,
                  avatar: '',
                  avatarOrigin: user.avatar,
                  detailTaskGuid: item.detailTaskGuid
                });
              }
            });
          }
        });
        item.usersInfo = users;
        item.rightFont = users.length + '人';
        state.moreTown = value;

        for (let i = 0; i < users.length; i++) {
          const user = users[i];
          await actions.setUserAvatar(user);
        }
      }

    };
    state.taskList.forEach(item => {
      const key = item.resKey;
      if (key) {
        if (key in keyMap) {
          keyMap[key](item, payload[key], payload);
        } else {
          item.value = payload[item.resKey];
        }
      }
    });
  },

  initData(state) {
    state.taskList = _.cloneDeep(initData.taskList);
    state.messageList = _.cloneDeep(initData.messageList);
    state.moreTown = _.cloneDeep(initData.moreTown);
    state.commentConfig = _.cloneDeep(initData.commentConfig);
    state.resData = {};
    const appRole = uni.getStorageSync('appRole');
    if (appRole) {
      if (appRole.includes('财政')) {
        const taskStatus = state.taskList.find(item => item.resKey === 'status');
        if (taskStatus) {
          taskStatus.action = null;
          taskStatus.showRightIcon = false;
        }
        state.taskList.splice(3, 0, _.cloneDeep(stakStatus));
      }
    }
  },

  initDataForComment(state) {
    state.messageList = _.cloneDeep(initData.messageList);
    state.commentConfig = _.cloneDeep(initData.commentConfig);
  },

  // 评论页数++
  pageIndexAdd(state, number) {
    state.commentConfig.pageIndex = number;
    state.commentConfig.isRequested = true;
  },

  // 评论赋值
  assignComment(state, payload) {
    if (Array.isArray(payload) && payload.length) {
      const cItem = {
        contentType: 2,
        cardMsg: {
          isHideBackWord: true,
          time: '',
          name: '',
          content: '',
          avatar: ''
        }
      };
      const content = [];

      payload.forEach(item => {
        const c = _.cloneDeep(cItem);
        const userId = uni.getStorageSync('userId');
        item.annexIds && item.annexIds.forEach(item => {
          item.img = state.baseUrl + 'file/downloadById' + `?id=${item.id}&fileName=${item.originName}`;
        });
        c.cardMsg = {
          ...c.cardMsg,
          ...item
        };
        c.cardMsg.isHideBackWord = userId + '' !== item.editUser + '';
        c.cardMsg.time = item.editTime;
        c.cardMsg.name = item.trueName;
        c.cardMsg.content = item.content;
        c.cardMsg.photolist = item.annexIds || [];
        content.push(c);
      });
      state.messageList.push(...content);
    }
  },

  // 验证乡镇任务是否驳回
  getTownReject(state, data) {
    const { enterpriseCode, xzStatus, xzRole, details } = data;
    if (xzRole) {
      bbq:
      for (let i = 0; i < details.length; i++) {
        for (let j = 0; j < details[i].users.length; j++) {
          if (details[i].users[j].cEnterpriseCode === enterpriseCode && details[i].users[j].isCheck === 1) {
            state.detailsOne = details[i];
            break bbq;
          } else {
            state.detailsOne = {};
          }
        }
      }
      const status = Number(xzStatus);
      if (status === 5 || status === 1 || status === 3) {
        state.townReject = true;
      } else {
        state.townReject = false;
      }
    }
    // const appRole = uni.getStorageSync('appRole');
    // const userId = uni.getStorageSync('userId');
    // if (appRole && appRole.includes('乡镇')) {
    //   const details = data.details;
    //   bbq:
    //   for (let i = 0; i < details.length; i++) {
    //     for (let j = 0; j < details[i].users.length; j++) {
    //       if (details[i].users[j].userId === userId && details[i].users[j].isCheck === 1) {
    //         state.detailsOne = details[i];
    //         break bbq;
    //       } else {
    //         state.detailsOne = {};
    //       }
    //     }
    //   }
    //   const status = Number(state.detailsOne.status);
    //   if (status === 5 || status === 1 || status === 3) {
    //     state.townReject = true;
    //   } else {
    //     state.townReject = false;
    //   }
    // }
  }
};

const actions = {
  setUrl({ commit }, url) {
    commit('assignBaseUrl', url);
  },

  actionToken: ({ commit, state }, info) => {
    state.userIdentity = info.trueName;
    commit('setToken', info.token);
  },

  // 用户头像
  setUserAvatar: async(user) => {
    const { avatarId: avatar, avatarOrigin: avatarId, userId } = user;
    // if (avatar || avatarId) {
    return await getUserAvatar({ avatarId, avatar, userId }).then(res => {
      if (res) {
        const users = state.taskList.find(item => item.resKey === 'details');
        users && users.usersInfo.forEach(item => {
          if (item.userId === userId) {
            item.avatar = res;
          }
        });
        return Promise.resolve(res);
      }
    });
    // }
  },

  // 详情
  async getTaskDetail({ commit, dispatch }, payload) {
    const reloadType = payload.reloadType;
    if (reloadType && reloadType === 'refreshMsgOnly') {
      dispatch('reloadMessage', payload);
      return;
    }
    commit('initData');
    uni.showLoading({
      title: '加载中'
    });
    getProjectDetial({
      programGuid: payload.programGuid,
      appId: getAppId(),
      year: new Date().getFullYear()
    }).then(async(res) => {
      setTimeout(() => {
        uni.hideLoading();
      }, 500);
      const { success, data } = res;
      payload.action && payload.action(res, '明细');
      if (success && typeof data === 'object') {
        const dealData = await dealDetailData(_.cloneDeep(data));
        const { status, xzRole, enterpriseCode } = payload;
        if (xzRole) {
          dealData.status = status;
        }
        commit('assignValueForTask', dealData);
        commit('getTownReject', { ...dealData, enterpriseCode, xzStatus: payload.status, xzRole });
      }
    });
    dispatch('getListComment', payload);
  },

  // 重新评论
  reloadMessage({ commit, dispatch }, payload) {
    commit('initDataForComment');
    dispatch('getListComment', payload);
  },

  getListComment(context, { taskGuid, action }) {
    const { state: { commentConfig, messageList }, commit } = context;
    if (commentConfig.isRequested && ((messageList.length) < commentConfig.pageSize)) {
      commit('commentConfigNomore');
      action && action(commentConfig, '评论');
      return;
    }
    const requestData = {
      taskGuid,
      ...commentConfig
    };

    listComment(requestData).then(async(res) => {
      const total = res.total;
      const isNext = commentConfig.pageIndex + 1 < Math.ceil(total / commentConfig.pageSize);
      res.isNext = isNext;
      action && action(res, '评论');
      if (res.success) {
        commit('pageIndexAdd', commentConfig.pageIndex + 1);
        commit('assignComment', res.data);
        // 获取头像
        if (Array.isArray(res.data)) {
          const userMap = {};
          res.data.forEach(user => {
            userMap[user.editUser] = user;
          });
          for (const key in userMap) {
            const { avatarId: avatar, avatar: avatarId, editUser, editUser: userId } = userMap[key];
            await getUserAvatar({ avatar, avatarId, userId }).then(img => {
              if (img) {
                commit('assginCommentUserAvatar', {
                  img,
                  editUser
                });
              }
            });
          }
        }
        if (total <= commentConfig.pageSize) {
          commit('commentConfigNomore');
        }
      }
    });
  }
};

const getters = {
  msgLength: state => {
    const len = state.messageList.length - 1;
    return len;
  }
};

const dealDetailData = data => {
  // 项目时间
  data.programTime = data.startTime + ' ~ ' + data.endTime;
  // 乡镇
  data.details.forEach(item => { item.enterpriseName = item.cEnterpriseName; });
  // 任务进度：status（1 进行中 2已完成 3已延期 4待审核 空 未发布）

  return data;
};

const initData = {
  taskList: _.cloneDeep(state.taskList),
  messageList: _.cloneDeep(state.messageList),
  moreTown: _.cloneDeep(state.moreTown),
  commentConfig: {
    pageType: 1,
    pageSize: 7,
    pageIndex: 0,
    isNextPage: true,
    isRequested: false // 是否请求过
  },
  resData: {}
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};

